import { useRef, useState } from 'react';
import { Form, Input, Button, Table, Space, Modal } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { getRoleList, deleteRole } from '@/api';
import { useEffect } from 'react';
import { PageParams, Role } from '@/types';
import { formatDate } from '@/utils';
import CreateRole from './createRole';
import { IAction } from '@/types/modal';
import { message } from '@/utils/AntdGlobal';
import SetPermission from './setPermission';

export default function RoleList() {
  const roleRef = useRef<{
    open: (type: IAction, data?: Role.CreateParams) => void;
  }>();
  const permissionRef = useRef<{
    open: (type: IAction, data?: Role.CreateParams) => void;
  }>();
  const [form] = Form.useForm();
  const handleSearch = async () => {
    getRoleListData({
      ...form.getFieldsValue(),
      pageNum: 1
    });
    form.resetFields();
  };

  const handleRest = () => {
    form.resetFields();
    getRoleListData({
      pageNum: 1
    });
  };

  const handleEditor = (record: Role.RoleItem) => () => {
    roleRef.current?.open('edit', record);
  };
  const handleDelete = (_id: string) => () => {
    Modal.confirm({
      title: '删除确认',
      content: <span>确定删除该角色吗</span>,
      onOk: async () => {
        try {
          await deleteRole({ _id });
          getRoleListData({
            pageNum: 1
          });
          message.success('删除成功');
        } catch (err) {
          message.success('删除失败');
          console.log(err);
        }
      }
    });
  };

  const handleTableChange = (current: number, pageSize: number) => {
    setPagination({
      current,
      pageSize
    });
  };

  const [roleList, setRoleList] = useState<Role.RoleItem[]>();
  const [total, setTotal] = useState<number>(0);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10
  });

  const getRoleListData = async (params: PageParams) => {
    const values = form.getFieldsValue();
    const data = await getRoleList({
      ...values,
      pageNum: params.pageNum,
      pageSize: params.pageSize || pagination.pageSize
    });
    setRoleList(data.list);
    setTotal(data.page.total);
  };

  const columns: ColumnsType<Role.RoleItem> = [
    {
      title: '角色名称',
      dataIndex: 'roleName',
      key: 'roleName'
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark'
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      render(updateTime: string) {
        return formatDate(updateTime);
      }
    },
    {
      title: '创建时间',
      key: 'createTime',
      dataIndex: 'createTime',
      render(createTime: string) {
        return formatDate(createTime);
      }
    },
    {
      title: '操作',
      key: 'opration',
      width: 100,
      render: (record: Role.RoleItem) => {
        return (
          <Space>
            <Button type='primary' onClick={handleSetPermission(record)}>
              设置权限
            </Button>
            <Button type='primary' onClick={handleEditor(record)}>
              编辑
            </Button>
            <Button type='primary' danger onClick={handleDelete(record._id)}>
              删除
            </Button>
          </Space>
        );
      }
    }
  ];

  useEffect(() => {
    getRoleListData({
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    });
  }, [pagination.current, pagination.pageSize]);

  const hanldeCreate = () => {
    roleRef.current?.open('create');
  };

  const handleSetPermission = (record: Role.RoleItem) => () => {
    permissionRef.current?.open('edit', record);
  };

  return (
    <div className='role-wrap'>
      <Form className='search-form' layout='inline' form={form}>
        <Form.Item label='角色名称' name='roleName'>
          <Input placeholder='请输入角色名称'></Input>
        </Form.Item>
        <Form.Item>
          <Button type='primary' className='mr10' onClick={handleSearch}>
            搜索
          </Button>
          <Button type='primary' danger onClick={handleRest}>
            重置
          </Button>
        </Form.Item>
      </Form>
      <div className='base-table'>
        <div className='header-wrapper'>
          <div className='title'>用户列表</div>
          <div className='action'>
            <Button type='primary' onClick={hanldeCreate}>
              新增
            </Button>
          </div>
        </div>
        <Table
          columns={columns}
          dataSource={roleList}
          bordered
          rowKey='_id'
          pagination={{
            position: ['bottomRight'],
            current: pagination.current,
            pageSize: pagination.pageSize,
            total,
            showTotal: total => {
              return `总共: ${total}条`;
            },
            onChange: handleTableChange
          }}
        />
      </div>
      <CreateRole
        mRef={roleRef}
        update={() =>
          getRoleListData({
            pageNum: 1
          })
        }
      ></CreateRole>
      <SetPermission
        mRef={permissionRef}
        update={() => {
          getRoleListData({
            pageNum: 1
          });
        }}
      ></SetPermission>
    </div>
  );
}
